package org.fungee.core;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Properties;

import org.fungee.core.exception.FungeeException;
import org.fungee.core.exception.LoadObjectAttributesFromPropertiesException;

public abstract class FungeeAttribute {

	protected void throwsException(String message, FungeeException exception) throws FungeeException{
		exception.setMessage(message);
		throw exception;
	}
	
	public void loadObjectAttributesFromProperties(Properties property) throws LoadObjectAttributesFromPropertiesException {
		Field fieldList[] = this.getClass().getFields();
		LoadObjectAttributesFromPropertiesException exception = new LoadObjectAttributesFromPropertiesException();
		for(Field field : fieldList){
			String fieldName = field.getName();
			if(property.containsKey(fieldName)){
				try{
					if(field.getGenericType() instanceof FungeeAttribute){
						FungeeAttribute fungeeAttribute;
						fungeeAttribute = (FungeeAttribute) field.get(this);
						fungeeAttribute.loadObjectAttributesFromProperties(property); 
					}
					else if(true){
						this.setAttribute(field, fieldName);
					}
					else{
						this.throwsException(" raised from " + this.getClass().getCanonicalName(), exception);
					}
						
				}catch (IllegalArgumentException e) {
					e.printStackTrace();
					this.throwsException(" raised from " + this.getClass().getCanonicalName() +" when a " + e.getClass().getCanonicalName() + " occur ", exception);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					this.throwsException(" raised from " + this.getClass().getCanonicalName() +" when a " + e.getClass().getCanonicalName() + " occur ", exception);
				} 
			}
		}
	}

	protected void setAttribute(Field field, String property) throws IllegalArgumentException, IllegalAccessException{
		Type type = field.getGenericType();
		if(type instanceof FungeeAttribute){
			FungeeAttribute fungeeAttribute = (FungeeAttribute) field.get(this);
			fungeeAttribute.setAttribute(property);
		}
	}

}
